package com.test.lucene;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;

public class SimpleLucene {
	public static void main(String[] args) throws Exception {
		createIndex("./luceneData", "./luceneIndex");
		searchIndex("./luceneIndex");
	}

	private static void createIndex(String dataDirs, String indexDirs)
			throws IOException, CorruptIndexException,
			LockObtainFailedException {
		File indexDir = new File(indexDirs);
		FSDirectory directory = FSDirectory.open(indexDir);
		
		Analyzer luceneAnalyzer = new StandardAnalyzer(Version.LUCENE_36);
		// 用来创建索引
		IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_36,
				luceneAnalyzer);
		// 添加此句话 是为了 只生成一系列index
		conf.setOpenMode(OpenMode.CREATE);
		
		IndexWriter indexWriter = new IndexWriter(directory, conf);
		
		File dataDir = new File(dataDirs);
		File[] dataFiles = dataDir.listFiles();
		
		long startTime = new Date().getTime();
		
		for (int i = 0; i < dataFiles.length; i++) {
			File file = dataFiles[i];
			if (file.isFile() && file.getName().endsWith(".txt")) {
				Document document = new Document();
				// 111111111 将标题 以key=bookname作为field
				// Field f = new Field("bookname",file.getName(), Store.YES,
				// Index.ANALYZED);
				// document.add(f);

				// 22222222222 将文件内容以content作为field存入
				Field content = new Field("content", new InputStreamReader(
						new FileInputStream(dataFiles[i]), "UTF-8"));
				document.add(content);
				Field fileName = new Field("fileName", file.getCanonicalPath(),
						Store.YES, Index.ANALYZED);
				document.add(fileName);
				indexWriter.addDocument(document);
			}
		}

		indexWriter.close();
		
		long endTime = new Date().getTime();
		
		System.out.println("It takes " + (endTime - startTime)
				+ " milliseconds to create index for the files in directory "
				+ dataDir.getPath());
	}

	// 简单索引
	public static void searchIndex(String filePath)
			throws CorruptIndexException, IOException, ParseException {
		File indexDir = new File(filePath);
		FSDirectory directory = FSDirectory.open(indexDir);
		IndexReader reader = IndexReader.open(directory);
		IndexSearcher searcher = new IndexSearcher(reader);

		// 11111
		// Term t = new Term("bookname","a.txt");
		// TermQuery quenry = new TermQuery(t);
		// //获得得分靠前的两个匹配记录
		// ScoreDoc[] docs = searcher.search(quenry, 2).scoreDocs;
		// for (int i = 0; i < docs.length; i++) {
		// Date start = new Date();
		// String bookname = searcher.doc(docs[i].doc).get("bookname");
		// Date end = new Date();
		// System.out.println(bookname + (end.getTime() - start.getTime())
		// + "ms");
		// }

		// 222222
		QueryParser parser = new QueryParser(Version.LUCENE_36, "content",
				new StandardAnalyzer(Version.LUCENE_36));
		Query query = parser.parse("AA");
		TopDocs results = searcher.search(query, null, 100);
		int hits = results.totalHits;
		ScoreDoc[] scoreDocs = results.scoreDocs;
		System.out.println(hits);
		for (ScoreDoc scoreDoc : scoreDocs) {
			Date start = new Date();

			Document doc = searcher.doc(scoreDoc.doc);
			String path = doc.get("fileName");
			System.out.println(">>hit : " + path);

			Date end = new Date();
			System.out.println((end.getTime() - start.getTime()) + "ms");
		}

	}
}
